
define(['ionic', 'services'], function () {
    angular.module('U9Mobile.services')
        .factory('AppManager', ['$q', '$http', '$cordovaFileTransfer', '$cordovaZip', '$cordovaFile', 'ConnectService', 'UserService', 'FileStorage', 'UtilService', 'AppConstants',
            function ($q, $http, $cordovaFileTransfer, $cordovaZip, $cordovaFile, ConnectService, UserService, FileStorage, UtilService, AppConstants) {
                var installApps = [],
                    activeAppName = '',
                    activeAppId = '',
                    appMgrDefer = $q.defer(),
                    o = {
                        loadingAppPromise: appMgrDefer.promise
                    };

                FileStorage.loadingPromise.then(function () {
                    installApps = FileStorage.get('installApps', []);
                    appMgrDefer.resolve();
                });

                o.checkLicense = function (appId) {
                    var defer = $q.defer();

                    var url = AppConstants.CHECK_LICENSE_URL.format({
                        address: ConnectService.getConnect('address'),
                        port: ConnectService.getConnect('port'),
                        appKey: appId,
                        userCode: UserService.getUserParams('account'),
                        businessId1:ConnectService.getConnect('company'),
                        businessId2:UserService.getUserParams('org').id
                    });
                    $http({
                        method: 'get',
                        url: url,
                        timeout: AppConstants.HTTP_TIME_OUT
                    }).success(function (data) {
                        defer.resolve(data);
                    }).error(function (error) {
                        defer.reject(error);
                    });

                    return defer.promise;
                };
                o.getAllApps = function () {
                    var defer = $q.defer();

                    var url = AppConstants.GET_ALL_APPS_URL.format({
                        address: ConnectService.getConnect('address'),
                        port: ConnectService.getConnect('port')
                    });
                    $http({
                        method: 'get',
                        url: url,
                        timeout: AppConstants.HTTP_TIME_OUT
                    }).success(function (data) {
                        defer.resolve(data.apps);
                    }).error(function () {
                        defer.reject();
                    });

                    return defer.promise;
                };
                o.setInstallApps = function (apps) {
                    installApps = apps;
                    return FileStorage.set('installApps', installApps);
                };
                o.getInstallApps = function () {
                    if (installApps.length === 0) {
                        return [];
                    }
                    var apps = angular.copy(installApps),
                        appDir;
                    for (var i in apps) {
                        appDir = UtilService.convertAppURL(apps[i].id + '/');
                        apps[i].imgquote = appDir + 'www/icon.png';
                        apps[i].imgquote1 = appDir + 'www/icon1.png';
                        apps[i].isUpdate = false;
                    }
                    return apps;
                };
                o.getUnInstallApps = function (allApps) {
                    if (allApps.length === 0) {
                        return [];
                    }
                    var unInstallApps = angular.copy(allApps);
                    for (var i = 0; i < unInstallApps.length; i++) {
                        for (var j = 0; j < installApps.length; j++) {
                            if (unInstallApps[i].id === installApps[j].id) {
                                unInstallApps.splice(i, 1);
                                --i;
                                break;
                            }
                        }
                    }
                    return unInstallApps;
                };
                o.checkUpdateAvailable = function (installApps, allApps) {
                    var updateAvailable = false;
                    for (var i = 0; i < installApps.length; i++) {
                        for (var j = 0; j < allApps.length; j++) {
                            if (installApps[i].id === allApps[j].id) {
                                if (installApps[i].version < allApps[j].version) {
                                    installApps[i].isUpdate = true;
                                    updateAvailable = true;
                                } else {
                                    installApps[i].isUpdate = false;
                                }
                                break;
                            }
                        }
                    }
                    return updateAvailable;
                };
                o.installApp = function (appId) {
                    var defer = $q.defer();

                    o.downloadApp(appId).then(function () {
                        var appDir = UtilService.getAppsDir() + appId + '/';
                        $cordovaFile.readAsText(appDir, AppConstants.APP_CONFIG_FILES_NAME).then(function (data) {
                            var tempStr = data.trim();
                            while (tempStr[0] !== '{') {
                                tempStr = tempStr.substring(1);
                            }
                            installApps.push(JSON.parse(tempStr));
                            FileStorage.set('installApps', installApps);
                            defer.resolve();
                        });
                    }, function () {
                        defer.reject();
                    });

                    return defer.promise;
                };
                o.unInstallApp = function (appId) {
                    var defer = $q.defer();

                    var len = installApps.length;
                    for (var i = 0; i < len; i++) {
                        if (installApps[i].id === appId) {
                            break;
                        }
                    }
                    if (i === len) {
                        defer.reject();
                    } else {
                        o.removeApp(appId).then(function () {
                            installApps.splice(i, 1);
                            FileStorage.set('installApps', installApps);
                            defer.resolve();
                        }, function () {
                            defer.reject();
                        });
                    }

                    return defer.promise;
                };
                o.updateApp = function (appId) {
                    var defer = $q.defer();

                    o.unInstallApp(appId).then(function () {
                        o.installApp(appId).then(function () {
                            defer.resolve();
                        }, function () {
                            defer.reject();
                        });
                    }, function () {
                        defer.reject();
                    });

                    return defer.promise;
                };
                o.downloadApp = function (appId) {
                    var defer = $q.defer();

                    if (window.cordova) {
                        var url = AppConstants.DOWNLOAD_APP_URL.format({
                            address: ConnectService.getConnect('address'),
                            port: ConnectService.getConnect('port'),
                            appId: appId
                        });
                        var fileURL = UtilService.getAppRootDir() + appId + '.zip';

                        $cordovaFileTransfer.download(url, fileURL).then(function () {
                            var targetURL = UtilService.getAppsDir();
                            $cordovaZip.unzip(fileURL, targetURL).then(function () {
                                $cordovaFile.removeFile(UtilService.getAppRootDir(), appId + '.zip').finally(function () {
                                    defer.resolve();
                                });
                            }, function () {
                                defer.reject();
                            });
                        }, function () {
                            defer.reject();
                        });
                    } else {
                        defer.reject();
                    }

                    return defer.promise;
                };
                o.removeApp = function (appId) {
                    var defer = $q.defer();
                    if (window.cordova) {
                        $cordovaFile.removeRecursively(UtilService.getAppsDir(), appId).then(function () {
                            defer.resolve();
                        }, function (error) {
                            defer.reject();
                        });
                    } else {
                        defer.reject();
                    }

                    return defer.promise;
                };
                o.setActiveAppId = function (appId) {
                    activeAppId = appId;
                };

                o.getActiveAppId = function () {
                    return activeAppId;
                };

                o.getActiveAppName = function (appId) {
                    angular.forEach(installApps, function (app) {
                        if (app.id === appId) {
                            activeAppName = app.name;
                        }
                    });
                    return activeAppName;
                };
                o.checkAppInstalled=function(appId){
                    var isInstalled=false;
                    for(var i=0;i<installApps.length;i++){
                        if(appId==installApps[i].id){
                            isInstalled=true;
                            break;
                        }
                    }
                    return isInstalled;
                }
                o.getActiveAppUrl = function () {
                    var appDir = UtilService.convertAppURL(activeAppId + '/');
                    return appDir + 'www/index.html' + '?mu=' + Math.random();
                };

                o.checkAppUpdate = function () {
                    var defer = $q.defer();

                    var _version = AppConstants.APP_VERSION,
                        os = '';
                    if (ionic.Platform.isAndroid()) {
                        os = 'android';
                    } else if (ionic.Platform.isIOS()) {
                        os = 'ios';
                    } else {
                        os = 'android';
                    }
                    var url = AppConstants.CHECK_UPDATE_URL.format({
                        address: FileStorage.get('address'),
                        port: FileStorage.get('port'),
                        os: os
                    });
                    $http({
                        method: 'get', 
                        url: url, 
                        timeout: AppConstants.HTTP_TIME_OUT
                    }).success(function (data) {
                        if (data.result && data.result[0] === 'E000') {
                            if (data.info[0] > _version) {
                                var msg = data.info[1] + '：' + data.info[2];
                                UtilService.confirm(msg).then(function (result) {
                                    if (result) {
                                        try {
                                            window.open(data.info[3], '_system', 'clearcache=yes');
                                        } catch (e) {
                                            UtilService.alert(e);
                                        }
                                    }
                                });
                            }
                        } else {
                            //UtilService.alert('检查更新失败');
                        }
                        defer.resolve();
                    }).error(function (data) {
                       /* if (data) {
                            UtilService.alert('检查更新失败');
                        } else {
                            UtilService.alert('网络信号弱或数据连接异常！');
                        }*/
                        defer.reject();
                    });

                    return defer.promise;
                };

                return o;
            }
        ]);
});